import serial import serial.tools.list_ports def find_serial_port(vendor_id, product_id): """Find and return the serial port for the given vendor ID and product ID.""" ports = serial.tools.list_ports.comports() for port in ports: if port.vid == vendor_id and port.pid == product_id: return port.device return None def send_command(ser, command): """Send a command over the serial connection.""" cmd = f"{command}\n" ser.write(cmd.encode()) # Send the command print(f"Sent command: {command}") # Define vendor and product IDs vendor_id = 0x0483 # STMicroelectronics vendor ID product_id = 0x5740 # STMicroelectronics Virtual COM Port product ID # Find the correct serial port device_path = find_serial_port(vendor_id, product_id) if device_path: print(f"Found device at {device_path}") try: # Open serial connection ser = serial.Serial(device_path, 9600, timeout=1) print(f"Connected to {device_path}") # Define available commands commands = { '1': '{"cmd":"firmware"}', '2': '{"cmd":"version"}', '3': '{"cmd":"serialno"}', '4': '{"cmd":"clear-screen: 0#0#319#479"}', '5': '{"cmd":"display-string: 20#8#24#hello world,this is my test line213"}', '6': '{"cmd":"foreground-color: #F800"}', '7': '{"cmd":"background-color: #F800"}', '8': '{"cmd":"display-qrcode: 10#10#100#text string"}', } # Show available commands to the user print("Select a command to send:") for key, value in commands.items(): print(f"{key}: {value}") # Get user input choice = input("Enter the number of the command you want to send: ") if choice in commands: # Send the selected command send_command(ser, commands[choice]) else: print("Invalid selection. Please choose a valid command number.") # Optionally, read the response response = ser.readline().decode().strip() print(f"Received: {response}") # Close the connection ser.close() except serial.SerialException as e: print(f"Error opening serial port: {e}") else: print("Device not found.")